package com.duowei.diandan.adapter;

import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.duowei.diandan.R;
import com.duowei.diandan.bean.Desk;
import com.duowei.diandan.databinding.DeskChoiceItemBinding;

import java.util.List;

public class DeskItemAdapter extends RecyclerView.Adapter<DeskItemAdapter.ViewHolder> {

    private List<Desk> mList;

    private OnDeskItemClickListener mOnDeskItemClickListener;

    public DeskItemAdapter(List<Desk> list, OnDeskItemClickListener onDeskItemClickListener) {
        mList = list;
        mOnDeskItemClickListener = onDeskItemClickListener;
    }

    public void setList(List<Desk> list) {
        mList = list;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        DeskChoiceItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),
                R.layout.recycler_item_desk_choice, parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Desk desk = mList.get(holder.getAdapterPosition());
        desk.setOnDataChangedListener(() -> notifyItemChanged(position));
        holder.mBinding.getRoot().setOnClickListener(v -> {
            if (mOnDeskItemClickListener != null) {
                mOnDeskItemClickListener.onDeskItemClick(desk);
            }
        });

        holder.bind(desk);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        DeskChoiceItemBinding mBinding;

        public ViewHolder(DeskChoiceItemBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }

        public void bind(Desk desk) {
            mBinding.setDesk(desk);
            mBinding.executePendingBindings();
        }
    }

    public interface OnDeskItemClickListener {
        void onDeskItemClick(Desk desk);
    }
}
